package com.lipi.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lipi.common.to.es.SkuEsModel;
import com.lipi.common.utils.R;
import com.lipi.mall.search.config.MallElasticSearchConfig;
import com.lipi.mall.search.constant.EsConstant;
import com.lipi.mall.search.feign.ProductFeignService;
import com.lipi.mall.search.service.MallSearchService;
import com.lipi.mall.search.vo.AttrResponseVO;
import com.lipi.mall.search.vo.BrandVO;
import com.lipi.mall.search.vo.SearchParam;
import com.lipi.mall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;


    @Autowired
    private ProductFeignService productFeignService;

    /**
     * @param searchParam 检索的所有参数
     * @return 返回的检索结果
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        //动态构建出查询需要的DSL语句
        SearchResult result = null;


        //准备检索请求
        SearchRequest searchRequest = buildSearchQequrest(searchParam);


        try {
            //执行检索
            SearchResponse response = client.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);

            //分析响应数据并封装格式
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }


    //准备检索请求

    /**
     * DSL 语句在resource目录DSL.json
     *
     * @return
     */
    private SearchRequest buildSearchQequrest(SearchParam param) {

        //DSL语句对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 查询：模糊匹配,过滤(按照属性，分类，品牌，价格区间，库存)
         */

        //1、构建 boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //1.1、根据检索关键字模糊匹配：must
        String keyword = param.getKeyword();
        if (StringUtils.isNotEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyword));
        }

        //1.2 过滤
        //1.2.1 按照catalog过滤
        Long catalogId = param.getCatalog3Id();
        if (catalogId != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", catalogId));
        }

        //1.2.2 按照catalog过滤
        List<Long> brandIds = param.getBrandId();
        if (!CollectionUtils.isEmpty(brandIds)) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", brandIds));
        }

        //1.2.3 按照attrs过滤
        List<String> attrs = param.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {


            for (String attrStr : attrs) {
                //attrs是嵌入式的，可以理解为sql中的 in (nested result)，需要单独构造查询体
                BoolQueryBuilder attrBoolQuery = QueryBuilders.boolQuery();

                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");

                attrBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                attrBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));


                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", attrBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }


        }

        //1.2.4 按照是否存在库存过滤 【0：无库存 1：有库存】默认有库存
        Integer hasStock = param.getHasStock();
        //若参数为0，查询无库存的,负责查询全部库存状态
        //todo 此处如此设计是为了节约造数据的操作，简化开发。
        // 实际上，我们应该是默认查询有库存的。
        if (hasStock != null && hasStock.equals(1)) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", false));
        }

        //1.2.5 按照价格区间查询
        String skuPrice = param.getSkuPrice();
        if (StringUtils.isNotEmpty(skuPrice)) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            //解析价格情况
            // _500   小于等于500
            // 1_500  1到500
            // 1_     大于等于1
            String[] s = StringUtils.split(skuPrice, "_");

            //区间
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else {
                int i = StringUtils.indexOf(skuPrice, "_");

                if (i == 0) {
                    // _xxx
                    rangeQuery.lte(s[0]);
                } else {
                    // xxx_
                    rangeQuery.gte(s[0]);
                }
            }


            boolQuery.filter(rangeQuery);
        }

        //封装查询部分数据
        sourceBuilder.query(boolQuery);

        /**
         * 排序,分页,高亮
         */

        //2.1排序
        String sort = param.getSort();
        if (StringUtils.isNotEmpty(sort)) {
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        //2.2分页
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        Integer pageNum = param.getPageNum();
        Integer from = (pageNum - 1) * EsConstant.PRODUCT_PAGESIZE;
        sourceBuilder.from(from);

        //2.3高亮,只有在模糊匹配时才有高亮功能
        if (StringUtils.isNotEmpty(keyword)) {

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");

            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */

        //3.1 品牌信息聚合
        //3.1.1 品牌信息聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(10);

        //3.1.1 品牌名-子聚合
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        brandAgg.subAggregation(brandNameAgg);

        //3.1.2 品牌图片-子聚合
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brandAgg.subAggregation(brandImgAgg);

        sourceBuilder.aggregation(brandAgg);

        //3.2 分类信息聚合
        // 3.2.1分类信息聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(10);

        //3.1.1 品牌名-子聚合
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1);
        catalogAgg.subAggregation(catalogNameAgg);

        sourceBuilder.aggregation(catalogAgg);


        //3.3 attr聚合 嵌入式聚合
        //3.3.1 attr聚合
        NestedAggregationBuilder attrsNestedAgg = AggregationBuilders.nested("attr_agg", "attrs");

        //3.3.1-1 attrId聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attrsNestedAgg.subAggregation(attrIdAgg);

        //3.3.1-2 attrName子聚合
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        attrIdAgg.subAggregation(attrNameAgg);

        //3.3.1-3 attrValue子聚合
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10);
        attrIdAgg.subAggregation(attrValueAgg);

        //3.3 end
        sourceBuilder.aggregation(attrsNestedAgg);

        //构建请求对象
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        String s = sourceBuilder.toString();
        System.out.println("构建的DSL语句：" + s);

        return searchRequest;
    }

    //构建结果数据
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {

        SearchResult result = new SearchResult();

        // 1、hit-返回查询到的所有数据
        SearchHits hits = response.getHits();

        //查询到的结果集
        SearchHit[] dataHits = hits.getHits();
        if (dataHits != null && dataHits.length > 0) {

            List<SkuEsModel> esModels = new ArrayList();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, new TypeReference<SkuEsModel>() {
                });

                String keyword = searchParam.getKeyword();
                if (StringUtils.isNotEmpty(keyword)) {
                    //keywords高亮设置
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String title = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(title);
                }
                esModels.add(skuEsModel);

            }
            result.setProducts(esModels);
        }

        // 2.分析聚合信息
        //获取所有聚合信息
        Aggregations aggregations = response.getAggregations();

        // 2.1、聚合-当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVO> attrVOS = new ArrayList<>();
        ParsedNested attrAgg = aggregations.get("attr_agg");
        // 2.1.1 聚合-属性id
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrBucket = attrIdAgg.getBuckets();
        for (Terms.Bucket bucket : attrBucket) {
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVO.setAttrId(attrId);

            // 2.1.2 属性名
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVO.setAttrName(attrName);

            // 2.1.2 属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValueList = attrValueAgg.getBuckets().stream().map(item -> {
                String attrValue = item.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVO.setAttrValue(attrValueList);

            // 2.1 end
            attrVOS.add(attrVO);
        }
        result.setAttrs(attrVOS);

        // 2.2、聚合-当前商品涉及到的品牌信息

        //2.2.1 获取品牌id
        List<SearchResult.BrandVO> brandVOs = new ArrayList<>();
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            long brandId = brandAggBucket.getKeyAsNumber().longValue();
            brandVO.setBrandId(brandId);

            // 2.2.2 获取品牌的名字
            ParsedStringTerms brandNameAgg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandName(brandName);
            // 2.2.3 获取品牌的图片
            ParsedStringTerms brandImgAgg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandImg(brandImg);


            //2.2 end
            brandVOs.add(brandVO);
        }
        result.setBrands(brandVOs);

        // 2.3、聚合-当前商品涉及到的分类信息
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();

        List<SearchResult.catalogVO> catalogVOS = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.catalogVO catalogVO = new SearchResult.catalogVO();

            //catalogId
            catalogVO.setCatalogID(Long.parseLong(bucket.getKeyAsString()));
            //catalogName 存储在子聚合中
            ParsedStringTerms catalogNameTerms = bucket.getAggregations().get("catalog_name_agg");
            Terms.Bucket catalogNameBucket = catalogNameTerms.getBuckets().get(0);
            String catalogName = catalogNameBucket.getKeyAsString();

            catalogVO.setCatalogName(catalogName);
            catalogVOS.add(catalogVO);
        }
        result.setCatalogs(catalogVOS);
        // 3.1、分页信息-页码

        result.setPageNum(searchParam.getPageNum());

        // 3.2、分页信息-总记录数

        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 3.3、分页信息-总页码
        Integer pageSize = EsConstant.PRODUCT_PAGESIZE;
        Integer pageNum;
        if ((int) total % pageSize == 0) {
            pageNum = (int) total / pageSize;
        } else {
            pageNum = ((int) total / pageSize) + 1;
        }
        result.setTotalPages(pageNum);

        // 3.4、分页信息-导航页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= pageNum; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 4、面包屑导航功能
        // 4.1: attrs面包屑
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            List<SearchResult.NavVo> navVos = searchParam.getAttrs().stream()
                    .map(attr -> {
                        SearchResult.NavVo navVo = new SearchResult.NavVo();
                        String[] s = attr.split("_");

                        navVo.setNavValue(s[1]);
                        R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                        
                        result.getAttrIds().add(Long.parseLong(s[0]));
                        if (r.getCode() == 0) {
                            AttrResponseVO data = r.getKey("attr", new TypeReference<AttrResponseVO>() {
                            });

                            navVo.setNavName(data.getAttrName());
                        } else {
                            navVo.setNavName(s[0]);
                        }
                        String replace = replaceQueryString(searchParam, attr, "attrs");

                        navVo.setLink("http://search.mall.com/list.html?" + replace);
                        return navVo;
                    })
                    .collect(Collectors.toList());

            result.setNavs(navVos);
        }

        // 4.2: brand面包屑
        List<Long> brandIds = searchParam.getBrandId();

        if (!CollectionUtils.isEmpty(brandIds)) {
            //防止前端上传相同值
            brandIds = brandIds.stream().distinct().collect(Collectors.toList());

            List<SearchResult.NavVo> navVOs = result.getNavs();

            R r = productFeignService.brandInfos(brandIds);
            Map<Long, BrandVO> brandVOMap = new HashMap<>();
            if (r.getCode() == 0) {
                List<BrandVO> data = r.getKey("data", new TypeReference<List<BrandVO>>() {
                });

                brandVOMap = data.stream().collect(Collectors.toMap(item -> {
                    return item.getBrandId();
                }, item -> {
                    return item;
                }));
            } else {

            }


            Map<Long, BrandVO> finalBrandVOMap = brandVOMap;


            List<SearchResult.NavVo> collect = brandIds.stream()
                    .map(brandId -> {
                        SearchResult.NavVo navVo = new SearchResult.NavVo();
                        navVo.setNavName("品牌");

                        BrandVO brandVO = finalBrandVOMap.get(brandId);
                        if (brandVO != null) {
                            navVo.setNavValue(brandVO.getName());
                        } else {
                        }

                        String replace = replaceQueryString(searchParam, String.valueOf(brandId), "brandId");
                        navVo.setLink("http://search.mall.com/list.html?" + replace);


                        return navVo;
                    })
                    .collect(Collectors.toList());

            navVOs.addAll(collect);
            result.setNavs(navVOs);
        }
        //todo  4.3: catagory面包屑


        return result;
    }

    private String replaceQueryString(SearchParam searchParam, String value, String key) {
        //取消该面包屑的跳转链接
        //取到所有的查询条件
        String encode = "";
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //attrs可能是第一个参数,若是第一个参数searchParam.get_queryString()取到的是以attrs开头的字符串
        String replace = searchParam.get_queryString().replace("&" + key + "=" + encode, "");
        replace = replace.replace(key + "=" + encode, "");
        return replace;
    }
}
